import React, { useEffect, useRef } from "react";
import * as echarts from "echarts";

interface LineChartProps {
  option?: echarts.EChartsOption;
}

const LineChart: React.FC<LineChartProps> = ({ option }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  // 判断无数据
  const isNoData =
    !option ||
    !option.series ||
    !Array.isArray(option.series) ||
    option.series.every((s: any) => !s.data || s.data.length === 0);

  console.log(isNoData, "option");
  useEffect(() => {
    if (isNoData) return;
    if (chartRef.current) {
      if (!chartInstance.current) {
        chartInstance.current = echarts.init(chartRef.current);
      }

      if (!isNoData && option) {
        const finalOption: echarts.EChartsOption = {
          tooltip: {
            trigger: "axis",
            formatter: (params: any) => {
              if (!Array.isArray(params)) return "";
              let html = params[0]?.axisValueLabel
                ? params[0].axisValueLabel + "<br/>"
                : "";
              params.forEach((item: any) => {
                let unit = "";
                if (item.seriesName && Array.isArray(option.series)) {
                  const found = (option.series as any[]).find(
                    (s) => s.name === item.seriesName
                  );
                  unit = found && found.unit ? found.unit : "";
                }
                html += `<span style='display:inline-block;margin-right:5px;
                  border-radius:10px;width:10px;height:10px;background:${item.color}'></span>
                  ${item.seriesName}: ${item.data}${unit}<br/>`;
              });
              return html;
            },
          },

          legend: {
            top: "top",
          },
          ...option,
          series: Array.isArray(option.series)
            ? option.series.map((s: any) => ({
                ...s,
                label: {
                  show: true,
                  position: "top",
                  formatter: (params: any) => {
                    return params.value + (s.unit || "");
                  },
                },
              }))
            : option.series,
        };
        chartInstance.current.setOption(finalOption, {
          notMerge: false,
          lazyUpdate: true,
        });
      }
    }

    return () => {
      chartInstance.current?.dispose();
      chartInstance.current = null;
    };
  }, [option, isNoData]);

  useEffect(() => {
    if (!chartRef.current || !chartInstance.current) return;
    const observer = new window.ResizeObserver(() => {
      chartInstance.current?.resize();
    });
    observer.observe(chartRef.current);
    return () => {
      observer.disconnect();
    };
  }, []);

  if (isNoData) {
    return (
      <div
        style={{
          width: "100%",
          height: 320,
          minWidth: 300,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          color: "#999",
        }}
      >
        暂无数据
      </div>
    );
  }
  return (
    <div ref={chartRef} style={{ width: "100%", height: 320, minWidth: 300 }} />
  );
};

export default LineChart;
